/*
 * @lc app=leetcode.cn id=2 lang=java
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      int carry = 0;
      ListNode result = null;
      ListNode temp = null;
      while(l1!=null || l2!=null) {
        int l1v = l1!=null?l1.val :0;
        int l2v = l2!=null?l2.val :0;
        int sum = l1v + carry + l2v;
        //判断是否有进位
        carry = sum>=10?1:0;
        int v = sum%10;
        if(result==null) {
          result =  new ListNode(v);
        }else{
          if(result.next==null) {
            result.next = new ListNode(v);
            temp = result.next;
          }else{
            temp.next = new ListNode(v);
            temp = temp.next;
          }
        }
        l1 = l1!=null?l1.next:null;
        l2 = l2!=null?l2.next:null;
      }
      if(carry==1) {
        if(temp==null ) {
          result.next = (new ListNode(1));
        }else {
          temp.next = (new ListNode(1));
        }
      }
      return result;
    }
}
// @lc code=end

